package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 * 用户信息管理 controller  组件
 * @author : zjj
 * @date : 2021/2/3 9:22
 */

@RestController
@RequestMapping("api/user/passport")
public class UserController {



    /**
     * 用户信息管理service组件
     */
    @Autowired
    private UserService userService;
    /**
     * redis操作模板
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     * @param userInfo  登录信息
     * @return          返回结果
     */
    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo){
        UserInfo info = userService.login(userInfo);
        if(info == null ){
            return Result.fail("用户名或者密码不正确");
        }
        String token = UUID.randomUUID().toString().replace("-","");

        HashMap<String,Object> map = new HashMap<>();

        map.put("nickName",info.getNickName());
        map.put("name",info.getName());
        map.put("token",token);
        // userKey = user:login:token
        String userKey = RedisConst.USER_LOGIN_KEY_PREFIX+token;
        // value = userId
        redisTemplate.opsForValue().set(userKey,info.getId().toString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);

        return Result.ok(map);
    }

    /**
     * 退出登录：
     *      删除缓存
     * @param request   请求
     * @return          返回结果
     */
    @GetMapping("logout")
    public Result logout(HttpServletRequest request){
        String token = request.getHeader("token");
        String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.delete(userKey);
        return Result.ok();
    }



}
